import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../utils/dio_util.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_icons/flutter_icons.dart';
import '../tabs.dart';
import '../../widget/my_dialog.dart';
class PasswordLogin extends StatefulWidget {
  PasswordLogin({this.loginType});

  final String loginType;

  @override
  _PasswordLoginState createState() => _PasswordLoginState();
}

class _PasswordLoginState extends State<PasswordLogin> {
  String userName = '123456'; //测试用的默认用户名
  String password = '123456'; //测试用的默认密码
  bool isBbscureText=true;
  bool autoValidate = false;
  TextEditingController _userNameController = TextEditingController(); //用户名
  TextEditingController _passwordController = TextEditingController(); //密码
  final passwordLoginFormKey = GlobalKey<FormState>();

  bool canLogin = true;
  @override
  void initState() {
    super.initState();
    initUsername();
  }

  @override
  void dispose() {
    super.dispose();
    _userNameController.dispose();
    _passwordController.dispose();
  }

  void initUsername() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    _userNameController.addListener(() {
      String getUserName = sp.getString('userName');
      setState(() {
        userName=getUserName;
      });
      if (userName != null) {
//        _userNameController.text = userName;
      }
      if (_passwordController.text.length > 3 &&
          _userNameController.text.length > 3) {
        setState(() {
          canLogin = true;
        });
      }
    });
  }

  //检测字段

  //验证密码
  String validatorPassword(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    }
    if (value.length < 3) {
      return '密码长度不能小于3';
    }
    return null;
  }

  //验证用户名
  String validatorUsername(value) {
    if (value.isEmpty) {
      return '用户名不能为空';
    }

    if (value.length < 3) {
      return '用户名长度不能小于3';
    }

    return null;
  }

  //确认登录
  doLogin() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    var api = '/api/mall/auth/login.service';
    MyDialog.loaddingDialog(context: context, title: '登陆中');
//     return false;
    if (passwordLoginFormKey.currentState.validate()) {
      setState(() {
        canLogin = true;
      });
      passwordLoginFormKey.currentState.save();
      var http = DioUtil();
      Map<String, dynamic> param = {'password': password, 'userName': userName};
      http.post(api, data:param).then((res) {
        if (res['code'] == 200) {
          var result = res['result'];
          sp.setString('userName', userName);
          sp.setString('token', result);
          //保存用户信息
          sp.setBool('isLogin', true);
//          Navigator.pop(context);
          Navigator.of(context)
              .pushReplacement(MaterialPageRoute(builder: (context) {
            return Tabs();
          }));
        } else {
          Navigator.pop(context);
          Fluttertoast.showToast(msg: res['msg']);
        }
      });
    } else {
      Navigator.pop(context);
      setState(() {
        autoValidate = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(
        primaryColor:Colors.red
      ),
      child: Form(
        key: passwordLoginFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
          TextFormField(
          controller: _userNameController,
          validator: validatorUsername,
          autovalidate: autoValidate,
          decoration: InputDecoration(
              suffix: IconButton(
                icon:Icon(Icons.close),
                onPressed: (){
                  _userNameController.text = '';
                },
              ),
              icon: Icon(Feather.user, size: 25),
              helperText: '',
              hintText: "请输入用户名",
              hintStyle: TextStyle(fontSize: 30.sp)),
          onChanged: (value){
            print(value);
            setState(() {
              userName = value;
            });
          },
          onSaved: (value) {
            // print(value);
            setState(() {
              userName = value;
            });
          },
        ),
            SizedBox(height: 10),
            TextFormField(
              controller: _passwordController,
              autovalidate: autoValidate,
              validator: validatorPassword,
              decoration: InputDecoration(
                suffix: IconButton(
                  icon: Icon(Icons.remove_red_eye,color: Colors.grey,),
                  onPressed: (){
                    setState(() {
                      isBbscureText=!isBbscureText;
                    });
                  },
                ),
                  icon: Icon(Icons.verified_user),
                  hintText: "请输入密码",
                  helperText: '',
                  hintStyle: TextStyle(fontSize: 30.sp)),
              obscureText: isBbscureText,
              onSaved: (value) {
                if (value.length > 3) {
                  setState(() {
                    canLogin = true;
                  });
                }
                setState(() {
                  password = value;
                });
              },
            ),
            SizedBox(height: 20),
            Container(
                width: 650.w,
                height: 90.h,
                child: RaisedButton(
                    child: Text(
                      "登录",
                      style: TextStyle(color: Colors.white, fontSize: 35.sp),
                    ),
                    color: Colors.red,
                    onPressed: canLogin == true ? doLogin : null)),
          ],
        ),
      ),
    );
  }
}
